<!--
 * @Author: atdow
 * @Date: 2021-07-17 09:29:49
 * @LastEditors: luojiajun
 * @LastEditTime: 2021-07-21 15:00:54
 * @Description: file description
-->
<template>
    <el-dialog title="编辑接口列表" :visible.sync="dialogVisible">
        <div class="user-rules-api">
            <div class="user-rules-api-header">
                <el-input
                    placeholder="输入关键字进行过滤"
                    suffix-icon="el-icon-search"
                    v-model="keyword"
                ></el-input>
            </div>
            <div class="user-rules-api-table">
                <el-tree
                    ref="tree"
                    :data="treeData"
                    node-key="id"
                    default-expand-all
                    show-checkbox
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    :default-checked-keys="defaultSelected"
                    @check-change="handleCheckChange"
                    @check="check"
                >
                    <div
                        class="custom-tree-node user-rules-api-table__main"
                        slot-scope="{ node, data }"
                    >
                        <div class="user-rules-api-table__main--td">
                            {{ data.dirName }}
                        </div>
                        <!-- TODO 全选和反选 -->
                        <div class="user-rules-api-table__main--td" v-if="0">
                            <el-checkbox-group
                                v-model="data.data.isManage"
                                @change="
                                    value => {
                                        filterSelect(
                                            data,
                                            value,
                                            node,
                                            'isManage'
                                        );
                                    }
                                "
                            >
                                <el-checkbox label="1">
                                    <span v-if="!data.isTable">全选</span>
                                    <span>{{ "" }}</span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                        <div class="user-rules-api-table__main--td" v-if="0">
                            <el-checkbox-group
                                v-model="data.data.isSubscribe"
                                @change="
                                    value => {
                                        filterSelect(
                                            data,
                                            value,
                                            node,
                                            'isSubscribe'
                                        );
                                    }
                                "
                            >
                                <el-checkbox label="1">
                                    <span v-if="!data.isTable">全选</span>
                                    <span>{{ "" }}</span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                </el-tree>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm" :loading="loading"
                >确 定</el-button
            >
        </span>
    </el-dialog>
</template>

<script>
import { editApiRole, getApiRole } from "@/api/dataManagement/system/user";
import { getApiTree } from "@/api/dataService/serviceMonitor/throttlingList";

export default {
    name: "UserRulesApiModal",
    model: {
        prop: "visible",
        event: "change"
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        userId: {
            type: String,
            default: ""
        },
        defaultSelected: {
            type: Array,
            default: () => {
                return [];
            }
        }
    },
    data() {
        return {
            loading: false,
            keyword: "",
            treeData: [],
            checkedKeys: []
        };
    },
    watch: {
        keyword(val) {
            this.$refs.tree.filter(val);
        },
        dialogVisible(value) {
            this.checkedKeys = [];
            if (value) {
                this.getApiRole();
            }
        }
    },
    computed: {
        dialogVisible: {
            get() {
                return this.visible;
            },
            set(newValue) {
                this.$emit("change", newValue);
            }
        }
    },
    methods: {
        handleCheckChange(data, checked, indeterminate) {
            // console.log(data, checked, indeterminate);
        },
        check(current, data) {
            const { checkedKeys = [] } = data;
            this.checkedKeys = checkedKeys;
            // console.log("checkedKeys:", checkedKeys);
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.dirName.indexOf(value) !== -1;
        },
        filterSelect(data, value, node, field) {
            return;
            // 选中字段
            if (node.level === 2) {
                let selected = this.isSelectedAllChildNodes(
                    node.parent.data.children,
                    field
                );
                node.parent.data.data[field] = selected;
                return;
            }
            // 选中表
            if (node.level === 1) {
                this.toggleSelectedAllChildNodes(
                    node.data.children,
                    field,
                    value == 1
                );
                return;
            }
        },
        /**
         * 判断是否选中所有子节点
         */
        isSelectedAllChildNodes(childNodes, field) {
            let isValid = true;
            for (let i = 0; i < childNodes.length; i++) {
                const childNode = childNodes[i];
                if (
                    !childNode.data[field].length ||
                    childNode.data[field] != 1
                ) {
                    isValid = false;
                    break;
                }
            }
            return isValid;
        },
        /**
         * 全选/反选
         */
        toggleSelectedAllChildNodes(childNodes, field, selected) {
            for (let i = 0; i < childNodes.length; i++) {
                const childNode = childNodes[i];
                childNode.data[field] = selected ? ["1"] : [];
            }
        },
        getApiRole() {
            getApiTree().then(res => {
                if (res.code === 200) {
                    this.initTableData(res.data);
                }
            });
            // getApiRole({ userId: this.userId })
            //     .then(res => {
            //         if (res.code === 200) {
            //             this.initTableData(res.data);
            //         }
            //     })
            //     .catch(() => {});
        },
        initTableData(tree) {
            // 获取用户树节点
            let treeData = JSON.parse(JSON.stringify(tree.children));
            let mesh = 1;
            recurion(treeData, 0);
            function recurion(list, parmentMesh) {
                list.forEach(listItem => {
                    listItem.mesh = parmentMesh + 1;
                    if (listItem.children && listItem.children.length > 0) {
                        recurion(listItem.children, listItem.mesh);
                    }
                });
            }
            this.treeData = treeData;
            // console.log("this.treeData:", this.treeData);
        },
        submitForm() {
            // console.log("checkedKeys:", this.checkedKeys);
            let formatCheckedKeys = [];
            this.checkedKeys.forEach(checkedKeysItem => {
                let flag = { id: checkedKeysItem, mesh: 1 };
                recursion(this.treeData, checkedKeysItem);
                function recursion(list, id) {
                    list.forEach(listItem => {
                        if (listItem.id === id) {
                            flag = { id: id, mesh: listItem.mesh };
                        }
                        if (listItem.children && listItem.children.length > 0) {
                            recursion(listItem.children, id);
                        }
                    });
                }
                if (flag.mesh === 2) {
                    formatCheckedKeys.push(checkedKeysItem);
                }
            });
            this.$emit("success", formatCheckedKeys);
            this.dialogVisible = false;
            // console.log("formatCheckedKeys:", formatCheckedKeys);
        }
    }
};
</script>

<style lang="scss" scoped>
.user-rules-api {
    &-header {
        margin-bottom: 20px;
    }

    &-table {
        max-height: 500px;
        overflow: auto;
        border: 1px solid #e6e6e6;
        user-select: none;

        &__header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            text-align: center;
            border-bottom: 1px solid #e6e6e6;

            &--th {
                padding: 0 10px;
                height: 50px;
                line-height: 50px;
                background: #f5f6fa;
                color: #1e1e1e;
                font-size: 16px;
                font-weight: 500;

                &:first-child {
                    flex: 1;
                }

                &:not(:first-child) {
                    width: 100px;
                    border-left: 1px solid #e6e6e6;
                }
            }
        }

        &__main {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;

            &--td {
                height: 40px;
                line-height: 40px;
                font-size: 16px;

                &:first-child {
                    flex: 1;
                    width: 600px;
                    padding-right: 10px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;  
                }

                &:not(:first-child) {
                    width: 100px;
                    text-align: center;
                }

                .el-checkbox {
                    width: 14px;
                    display: inline;
                }
            }
        }
    }

    ::v-deep .el-tree-node__content {
        height: 40px;
        line-height: 40px;
    }
}
</style>
